package delayqueue

import (
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

var Config *config

// config ...
type config struct {
	Namespace string
	RedisCli  *redis.Client
}

// Configure ...
func Configure(options map[string]string) {
	if options["addr"] == "" {
		panic("redis addr err")
	}

	var poolSize int
	if tmp, err := strconv.Atoi(options["pool_size"]); err == nil {
		poolSize = tmp
	} else {
		poolSize = 10
	}

	var db int
	if tmp, err := strconv.Atoi(options["db"]); err == nil {
		db = tmp
	} else {
		db = 1
	}

	var dialTimeout time.Duration
	if tmp, err := strconv.Atoi(options["dial_timeout"]); err == nil {
		dialTimeout = time.Duration(tmp)
	} else {
		dialTimeout = 5 * time.Second
	}

	redisCli := redis.NewClient(&redis.Options{
		Addr:        options["addr"],
		Password:    options["password"],
		DB:          db,
		DialTimeout: dialTimeout,
		PoolSize:    poolSize,
	})

	if _, err := redisCli.Ping().Result(); err != nil {
		panic(err)
	}

	var namespace string
	if options["namespace"] != "" {
		namespace = options["namespace"] + ":"
	}

	Config = &config{
		RedisCli:  redisCli,
		Namespace: namespace,
	}
}
